<template>
  <div class="create-order">
    <s-header :name="'生成订单'" @callback="deleteLocal"></s-header>

    <!-- 地址信息 -->
    <div class="address-wrap" v-if="deliveryType === 2 && address.addressId">
      <div class="name" @click="goToAddress">
        <span>{{ address.userName }} </span>
        <span>{{ address.userPhone }}</span>
      </div>
      <div class="address">
        {{ address.provinceName }} {{ address.cityName }} {{ address.regionName }} {{ address.detailAddress }}
      </div>
      <van-icon class="arrow" name="arrow" />
    </div>

    <!-- 快递方式但未选择地址 -->
    <div class="address-wrap select-address" v-else-if="deliveryType === 2 && !address.addressId" @click="goToAddress">
      <div class="name">
        <span>请选择收货地址</span>
      </div>
      <van-icon class="arrow" name="arrow" />
    </div>

    <!-- 自提地址信息 -->
    <div class="address-wrap" v-else-if="deliveryType === 1">
      <div class="name">
        <span>自提</span>
      </div>
      <div class="address">
        {{ selectedPickupAddress }}
      </div>
    </div>

    <!-- 配送方式选择 -->
    <div class="delivery-wrap">
      <div class="delivery-title">配送方式</div>
      <van-radio-group v-model="deliveryType">
        <van-cell-group>
          <van-cell title="自提" clickable @click="handleDeliveryTypeChange(1)" :class="{ 'selected-cell': deliveryType === 1 }">
            <template #right-icon>
              <van-radio :name="1" checked-color="#ee0a24" />
            </template>
            <div class="delivery-desc">到店自取，免运费</div>
          </van-cell>
          <van-cell title="快递" clickable @click="handleDeliveryTypeChange(2)" :class="{ 'selected-cell': deliveryType === 2 }">
            <template #right-icon>
              <van-radio :name="2" checked-color="#ee0a24" />
            </template>
            <div class="delivery-desc">快递配送，运费: ¥{{ deliveryFee }}</div>
          </van-cell>
        </van-cell-group>
      </van-radio-group>

      <!-- 自提地址选择 -->
      <div class="pickup-address-wrap" v-if="deliveryType === 1">
        <div class="pickup-title">选择自提地址</div>
        <van-radio-group v-model="selectedPickupAddress">
          <van-cell-group>
            <van-cell
              v-for="(addr, index) in pickupAddresses"
              :key="index"
              :title="addr"
              clickable
              @click="selectedPickupAddress = addr"
              :class="{ 'selected-cell': selectedPickupAddress === addr }"
            >
              <template #right-icon>
                <van-radio :name="addr" checked-color="#ee0a24" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="good">
      <div class="good-item" v-for="(item, index) in cartList" :key="index">
        <div class="good-img"><img :src="prefix(item.goodsCoverImg)" alt=""></div>
        <div class="good-desc">
          <div class="good-title">
            <span class="goods-name">{{ item.goodsName }}</span>
            <span class="goods-count">x{{ item.goodsCount }}</span>
          </div>
          <!-- 规格信息显示 -->
          <div class="good-specs" v-if="item.specText">
            <span class="spec-text">{{ item.specText }}</span>
          </div>
          <div class="good-btn">
            <div class="price">¥{{ item.sellingPrice }}</div>
            <!-- 移除单个商品的运费显示 -->
          </div>
        </div>
      </div>
    </div>

    <!-- 支付信息 -->
    <div class="pay-wrap">
      <div class="price-item">
        <span>商品金额</span>
        <span>¥{{ total }}</span>
      </div>
      <div class="price-item" v-if="deliveryType === 2 && deliveryFee > 0">
        <span>快递费</span>
        <span>¥{{ deliveryFee }}</span>
      </div>
      <div class="price-item total-price">
        <span>应付总额</span>
        <span>¥{{ finalTotal }}</span>
      </div>
      <van-button @click="createOrder" class="pay-btn" color="#1baeae" type="primary" block>生成订单</van-button>
    </div>

    <van-popup
      closeable
      :close-on-click-overlay="false"
      v-model="showPay"
      position="bottom"
      :style="{ height: '30%' }"
      @close="close"
    >
      <div :style="{ width: '90%', margin: '0 auto', padding: '50px 0' }">
        <van-button color="#4fc08d" block @click="payOrder(2)">微信支付</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import sHeader from '@/components/SimpleHeader'
import { getCart, getByCartItemIds } from '../service/cart'
import { getDefaultAddress, getAddressDetail } from '../service/address'
import { createOrder, payOrder, payWxOrder, getDeliveryFeeConfig } from '../service/order'
import { setLocal, getLocal } from '@/common/js/utils'
import { Toast } from 'vant'

export default {
  components: {
    sHeader
  },
  data() {
    return {
      cartList: [],
      address: {},
      showPay: false,
      orderNo: '',
      cartItemIds: [],
      deliveryType: 1, // 1-自提 2-快递
      deliveryFee: 0, // 直接从数据库读取的总运费
      // 自提地址列表
      pickupAddresses: [
        '丁家庄院区818自提',
        '莫愁路院区2号楼410办公室自提'
      ],
      selectedPickupAddress: '丁家庄院区818自提', // 默认选择第一个
      // 保存路由参数，防止刷新丢失
      routeParams: {}
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      Toast.loading({ message: '加载中...', forbidClick: true });

      // 从路由参数获取配送方式
      const { addressId, cartItemIds, deliveryType } = this.$route.query

      // 设置配送方式，优先使用路由参数
      if (deliveryType) {
        this.deliveryType = parseInt(deliveryType)
      }

      const _cartItemIds = cartItemIds ? JSON.parse(cartItemIds) : JSON.parse(getLocal('cartItemIds'))
      setLocal('cartItemIds', JSON.stringify(_cartItemIds))
      this.cartItemIds = _cartItemIds

      // 获取购物车商品列表
      const { data: list } = await getByCartItemIds({ cartItemIds: _cartItemIds.join(',') })
      this.cartList = list

      // 计算快递费 - 现在只需要从数据库读取总运费
      await this.calculateDeliveryFee()

      // 根据配送方式加载地址信息
      if (this.deliveryType === 2) {
        await this.loadAddress(addressId)
      }

      Toast.clear()
    },

    async loadAddress(addressId) {
      try {
        // 优先使用传入的addressId，如果没有则使用默认地址
        let addressData = {}
        if (addressId) {
          const { data } = await getAddressDetail(addressId)
          addressData = data || {}
        } else {
          const { data } = await getDefaultAddress()
          addressData = data || {}
        }

        if (addressData.addressId) {
          this.address = addressData
        } else {
          // 没有地址，清空当前地址
          this.address = {}
        }
      } catch (error) {
        console.error('加载地址失败:', error)
        this.address = {}
      }
    },

    async calculateDeliveryFee() {
      try {
        // 调用后端接口获取总运费
        const { data, resultCode } = await getDeliveryFeeConfig()
        if (resultCode === 200 && data && data.defaultFee) {
          this.deliveryFee = parseFloat(data.defaultFee)
          console.log('从数据库读取的总运费:', this.deliveryFee)
        } else {
          this.deliveryFee = 0
          console.log('未找到运费配置，使用默认值0')
        }
      } catch (error) {
        console.error('获取运费配置失败:', error)
        this.deliveryFee = 0
      }
    },

    goToAddress() {
      this.$router.push({
        path: `address`,
        query: {
          cartItemIds: JSON.stringify(this.cartItemIds),
          deliveryType: this.deliveryType,
          from: 'createOrder'
        }
      })
    },

    handleDeliveryTypeChange(type) {
      this.deliveryType = type

      // 更新URL，防止刷新后丢失状态
      this.updateRouteParams()

      // 如果切换到快递方式且没有地址，跳转到地址选择
      if (type === 2 && !this.address.addressId) {
        this.goToAddress()
      }
    },

    updateRouteParams() {
      // 更新URL参数但不刷新页面
      const query = {
        ...this.$route.query,
        deliveryType: this.deliveryType
      }
      // 如果当前有地址，也保留地址ID
      if (this.address.addressId) {
        query.addressId = this.address.addressId
      }
      this.$router.replace({ query })
    },

    deleteLocal() {
      setLocal('cartItemIds', '')
    },

    async createOrder() {
      if (!this.deliveryType) {
        Toast.fail('请选择配送方式')
        return
      }

      // 如果是自提方式，验证自提地址
      if (this.deliveryType === 1 && !this.selectedPickupAddress) {
        Toast.fail('请选择自提地址')
        return
      }

      // 如果是快递方式，验证收货地址
      if (this.deliveryType === 2 && !this.address.addressId) {
        Toast.fail('请选择收货地址')
        return
      }

      const params = {
        cartItemIds: this.cartList.map(item => item.cartItemId),
        deliveryType: this.deliveryType
      }

      // 根据配送方式设置不同的地址参数
      if (this.deliveryType === 2) {
        params.addressId = this.address.addressId
      } else {
        params.pickupAddress = this.selectedPickupAddress
      }

      Toast.loading('生成订单中...')
      try {
        const { data, resultCode } = await createOrder(params)
        if (resultCode === 200) {
          setLocal('cartItemIds', '')
          this.orderNo = data
          this.showPay = true
          Toast.clear()
        }
      } catch (error) {
        Toast.fail('生成订单失败')
        console.error('生成订单失败:', error)
      }
    },

    close() {
      this.$router.push({ path: 'order' })
    },

    async payOrder(type) {
      Toast.loading('支付中...')
      try {
        await payWxOrder({ orderNo: this.orderNo, payType: type })
      } catch (error) {
        Toast.fail('支付失败')
        console.error('支付失败:', error)
      }
    }
  },
  computed: {
    total: function() {
      let sum = 0
      this.cartList.forEach(item => {
        sum += item.goodsCount * item.sellingPrice
      })
      return sum.toFixed(2)
    },
    finalTotal: function() {
      if (this.deliveryType === 1) {
        return this.total
      } else {
        return (parseFloat(this.total) + parseFloat(this.deliveryFee)).toFixed(2)
      }
    }
  },
  watch: {
    // 监听路由变化，当从地址选择页面返回时重新初始化
    '$route.query': {
      handler(newQuery) {
        if (newQuery.addressId || newQuery.deliveryType) {
          this.init()
        }
      },
      immediate: true,
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
@import '../common/style/mixin';
.create-order {
  background: #f9f9f9;

  .address-wrap {
    margin-bottom: 20px;
    background: #fff;
    position: relative;
    margin-top: 44px;
    font-size: 14px;
    padding: 15px;
    color: #222333;
    .name, .address {
      margin: 10px 0;
    }
    .arrow {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
    }
    &.select-address {
      background: #f8f8f8;
      color: #999;
      text-align: center;
      .name span {
        color: #1989fa;
      }
    }
    &::before {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
      background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
      background-size: 80px;
      content: '';
    }
  }

  .delivery-wrap {
    background: #fff;
    margin-bottom: 20px;
    padding: 15px;
    .delivery-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #333;
    }

    .selected-cell {
      background-color: #f0f9ff;
      border-left: 3px solid #1989fa;
    }

    .van-cell {
      border-radius: 8px;
      margin-bottom: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);

      .delivery-desc {
        font-size: 12px;
        color: #666;
        margin-top: 4px;
      }
    }

    .pickup-address-wrap {
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #f5f5f5;
      .pickup-title {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 10px;
        color: #333;
      }

      .van-cell {
        margin-bottom: 5px;
      }
    }
  }

  .good {
    margin-bottom: 120px;
  }
  .good-item {
    padding: 10px;
    background: #fff;
    display: flex;
    border-bottom: 1px solid #f5f5f5;
    .good-img {
      img {
        .wh(100px, 100px)
      }
    }
    .good-desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      padding: 20px;
      .good-title {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 8px;
        .goods-name {
          flex: 1;
          font-size: 14px;
          color: #333;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-camp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-right: 10px;
        }
        .goods-count {
          font-size: 14px;
          color: #999;
          white-space: nowrap;
        }
      }
      .good-specs {
        margin-bottom: 12px;
        .spec-text {
          display: inline-block;
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
          padding: 4px 8px;
          border-radius: 4px;
          line-height: 1.2;
        }
      }
      .good-btn {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .price {
          font-size: 16px;
          color: #ee0a24;
          line-height: 28px;
          font-weight: bold;
        }
        /* 移除单个商品的运费显示 */
      }
    }
  }
  .pay-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    padding: 10px 0;
    padding-bottom: 50px;
    border-top: 1px solid #e9e9e9;
    .price-item {
      display: flex;
      justify-content: space-between;
      padding: 0 5%;
      margin: 10px 0;
      font-size: 14px;
      span:nth-child(2) {
        color: #333;
        font-size: 16px;
      }
      &.total-price {
        border-top: 1px solid #e9e9e9;
        padding-top: 10px;
        margin-top: 15px;
        span:nth-child(2) {
          color: red;
          font-size: 18px;
          font-weight: bold;
        }
      }
    }
    .pay-btn {
      position: fixed;
      bottom: 7px;
      right: 0;
      left: 0;
      width: 90%;
      margin: 0 auto;
    }
  }
}
</style>
